##########################################################################################################
# REPLICATION CODE FOR                                                                                   #
# "Conspiracy beliefs and perceptions of electoral integrity: Cross-national evidence from 29 countries" #
# PUBLIC OPINION QUARTERLY																										                           #
#																																                                         #
# AUTHOR: Christian Schnaudt (corresponding author)                                                      #
# ADDRESS: School of Social Sciences, University of Mannheim, 68131 Mannheim, Germany                    # 
# E-MAIL: schnaudt@uni-mannheim.de 																								                       #
# ORCID: 0000-0002-2062-7770																									                           #   
#																																                                         #
# VERSION DATE: 2023-10-06							                                                                 #   
##########################################################################################################


# REPLICATION CODE FOR CREATING FIGURES 1-4 (SEE MAIN ANALYSIS IN TEXT) AND S1-S3 (SEE SUPPLEMENTARY MATERIAL)

# IMPORTANT: RUN THE BELOW CODE ONLY AFTER RUNNING the FILE "analysis_models.R"
# (and using the R workspace created by "analysis_models.R")


################################################################################

# Figure 1

# Preparatory steps

# divide dependent variable by 10 to have same scale as conspiracy beliefs
ess$fairelcc_nm<-(ess$fairelcc)/10

#country means for coloring
ess <- ess[,-1]

ess_cmean<-ess %>%
  dplyr::group_by(cntry) %>%
  tibble::rownames_to_column() %>%
  dplyr::summarize(fairelcc_cmean = mean(fairelcc,na.rm=T, weights=anweight),
                   conspi_cmean = mean(conspi_nm,na.rm=T, weights=anweight))

table(ess_cmean$fairelcc_cmean, ess_cmean$cntry)

#add group means to ess
ess <- ess %>% 
  left_join(ess_cmean, by = c("cntry" = "cntry"))

# color variable based on mean of electoral integrity perceptions
summary(ess$fairelcc_cmean)

ess$colormean_fair = ifelse(ess$fairelcc_cmean < 7.316, 1, 0)
summary(ess$colormean_fair)
table(ess$colormean_fair)
ess$colormean_fair<-as.factor(ess$colormean_fair)


# CREATE PANEL A OF FIGURE 1
panelA_fig1<-ggplot(ess, aes(cname, fairelcc, colour = colormean_fair)) +
  geom_hline(yintercept = 7.316, colour="red1", linewidth=1, linetype = "longdash") +
  stat_summary(fun="mean", geom="point", size=6, alpha=.4) +
  stat_summary(fun.data = "mean_cl_normal", 
               geom = "errorbar", 
               width = .3, linewidth=.75) +
  scale_color_manual(values = c("black", "grey60")) +
  coord_flip() +
  theme_sjplot2() +
  labs(x = "", y = "National elections free and fair (0-10)", title = "(A)") +
  scale_x_continuous(breaks = c(0, 0.5, 1), labels=c("0" = "min", "0.5" = "medium", "1" = "max")) +
  theme(axis.text.x = element_text(face="bold", color="#000000", size=14, angle=0)) +
  scale_y_continuous(breaks = c(0,10), labels=c("0"="min", "10"="max"), limits = c(0,10)) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text.y = element_text(face="bold", color="#000000", 
                                   size=16, angle=0)) +
  theme(axis.title.x = element_text(color="#000000", face="bold", size=16, margin = margin(t = 10, r = 0, b = , l = 0))) +
  theme(axis.title.y = element_text(color="#000000", face="bold", size=16, margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  theme(plot.title = element_text(face = "bold", size=20)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(panel.spacing = unit(2, "lines")) +
  theme(legend.position = "none") +
  xlim(rev(levels(ess$cntry2)))

panelA_fig1

##############################################################


# color variable based on mean of conspiracy beliefs
ess$colormean_conspi = ifelse(ess$conspi_cmean < 0.3964, 1, 0)
summary(ess$colormean_conspi)
table(ess$colormean_conspi)
ess$colormean_conspi<-as.factor(ess$colormean_conspi)

# CREATE PANEL B OF FIGURE 1
panelB_fig1<-ggplot(ess, aes(cntry, conspi_nm, color = colormean_conspi)) +
  geom_hline(yintercept = 0.3964, colour="red", linewidth=1, linetype = "longdash") +
  stat_summary(fun="mean", geom="point", size=6, alpha=.3) +
  stat_summary(fun.data = "mean_cl_normal", 
               geom = "errorbar", 
               width = .3, linewidth=.75) +
  #gghighlight(colormean_fair == "1") +
  scale_color_manual(values = c("black", "grey60")) +
  coord_flip() +
  theme_sjplot2() +
  labs(x = "", y = "Belief in conspiracy theories (0-1)", title = "(B)") +
  scale_x_continuous(breaks = c(0, 0.5, 1), labels=c("0" = "min", "0.5" = "medium","1" = "max")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text.x = element_text(face="bold", color="#000000", size=14, angle=0)) +
  scale_y_continuous(breaks = c(0,1), labels=c("0"="min", "1"="max"), limits = c(-0.25,1.25)) +
  theme(axis.text.y = element_text(face="bold", color="#000000", size=16, angle=0)) +
  theme(axis.title.x = element_text(color="#000000", face="bold", size=16, margin = margin(t = 10, r = 0, b = , l = 0))) +
  theme(axis.title.y = element_text(color="#000000", face="bold", size=16, margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  theme(plot.title = element_text(face = "bold", size=20)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(legend.position = "none") +
  theme(panel.spacing = unit(2, "lines")) +
  xlim(rev(levels(ess$cntry))) +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

panelB_fig1


##############################################################

# save Figure 1

ggarrange(panelA_fig1, panelB_fig1, ncol = 2)

ggsave(filename = "Fig1.svg", 
       width=13, height=9, dpi = 1200) 

ggsave(filename = "Fig1.pdf", 
       width=13, height=9, dpi = 1200) 

ggsave("Fig1.eps", device=cairo_ps, 
       width=13, height=9, fallback_resolution = 1200)


#############################################################################

# FIGURE 2

fig2<-plot_models(model8, model6, grid = T, transform = NULL, show.p=F, show.values = T, p.shape = F,
                       axis.title = "Coefficients (with 95% confidence intervals)", 
                       legend.title = "", show.legend = F, vline.color = "red1",
                       colors= c("black", "black"), dot.size = 6, line.size = .75, 
                       wrap.labels = 55,
                       m.labels = c("Model 2\n(cross-level interaction)", "Model 1\n(direct effects)"),
                       axis.labels = c(
                         conspi_nm = "Conspiracy beliefs",
                         distrst_nm = "Distrust in politics",
                         stfeco_nm = "Economic satisfaction",
                         polintr_nm = "Political interest",
                         inteff_nm = "Internal efficacy",
                         lrscale_nm = "L-R placement",
                         pid = "Party ID",
                         "winner2Winner" = "Electoral winner vs. loser: Winner (vs. loser)",
                         "winner2Non-voters" = "Non-voter (vs. loser)",
                         "winner2Voters (w/o status)" = "Voter w/ unknown W/L status (vs. loser)",
                         "winner2Ineligibles" = "Ineligibles (vs. loser)",
                         meduse_nm = "Media use",
                         age_nm = "Age",
                         female = "Female", 
                         eduyrs_nm = "Education (years)",
                         "modeF2F" = "cc",
                         "modeVideo interview" = "Survey mode: Video interview (vs. F2F)",
                         "modeSelf-admin: web" = "Self-admin: web (vs. F2F)",
                         "modeSelf-admin: paper" = "Self-admin: paper (vs. F2F)",
                         ei_index_vdem = "Electoral integrity (country)",
                         gdppc_nm = "GDP per capita (country)",
                         "v2elcomvot" = "Compulsory voting (country)",
                         "conspi_nm:ei_index_vdem" = "Conspiracy beliefs * Electoral integrity (country)")) +
  theme_sjplot2() +
  aes(shape = group) +
  scale_shape_manual(values = c(2, 2)) +
  theme(axis.title.x = element_text(face="bold", size=16, margin = margin(t = 10, r = 0, b = , l = 0))) +
  theme(axis.text.y = element_text(face="bold", size=17)) +
  theme(axis.text.x = element_text(face="bold", size=13)) +
  theme(strip.text.x = element_text(face="bold", size=18)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(panel.spacing = unit(1, "lines"))

fig2

# fine tuning
# vline
fig2$layers[[1]]$aes_params$size <- 1.15
# labels
fig2$layers[[4]]$aes_params$size <- 5
# pos of values next to dots
fig2$layers[[4]]$aes_params$vjust<-(-0.4)
fig2$layers[[4]]$aes_params$hjust<-(-0.3)

fig2

##############################################################

# save Figure 2

ggsave(filename = "Fig2.pdf", 
       width=12, height=11, dpi = 1200) 

ggsave(filename = "Fig2.svg", 
       width=12, height=11, dpi = 1200) 

ggsave("Fig2.eps", device=cairo_ps, 
       width=12, height=11, fallback_resolution = 1200)

#############################################################################

# FIGURE 3

# random intercepts/effects of conspiracy beliefs across countries for FINAL MODEL
summary(model6c)
fixef(model6c)
ranef(model6c)

fig3<-plot_model(model6c, sort.est = "(Intercept)", type="re", show.p=T, show.values = T, value.offset = .4,
                     colors= c("grey60", "black"), show.legend = F,
                     dot.size = 6, line.size = .75, vline.color = "red") +
  #geom_hline(yintercept=0, color="red") +
  aes(shape = group) +
  scale_shape_manual(values = c(2, 2)) +
  theme_sjplot2() +
  labs(x = "", y = "Coefficients (random effects with 95% confidence intervals)", 
       title = "", legend="") +
  theme(axis.title.x = element_text(face="bold", size=16, margin = margin(t = 10, r = 0, b = , l = 0))) +
  theme(axis.text.y = element_text(face="bold", size=17)) +
  theme(axis.text.x = element_text(face="bold", size=13)) +
  theme(strip.text.x = element_text(face="bold", size=18)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(panel.spacing = unit(1, "lines")) +
  theme(legend.position = "none")
fig3

# fine tuning
fig3$data$facet
fig3$data$facet <- factor(fig3$data$facet)
levels(fig3$data$facet)
levels(fig3$data$facet)<- c("Country (intercept)", "Conspiracy beliefs (slope)")
fig3$layers
# vline
fig3$layers[[1]]$aes_params$size <- 1.15
# labels
fig3$layers[[4]]$aes_params$size <- 5
# pos of values next to dots
fig3$layers[[4]]$aes_params$vjust<-(0.75)
fig3$layers[[4]]$aes_params$hjust<-(-0.6)

fig3

##############################################################

# save Figure 3

ggsave(filename = "Fig3.pdf", 
       width=12, height=11, dpi = 1200) 

ggsave(filename = "Fig3.svg", 
       width=12, height=11, dpi = 1200) 

ggsave("Fig3.eps", device=cairo_ps, 
       width=12, height=11, fallback_resolution = 1200)

#############################################################################


# FIGURE 4

summary(model8)

# PANEL A: Conditional marginal effects 

panelA_fig4 <- interplot(model8, var1 = "conspi_nm", var2 = "ei_index_vdem", hist=F) +
  xlab("Electoral integrity (country level)") +
  ylab("Conditional marginal effects:\nConspiracy beliefs") +
  scale_x_continuous(limits = c(0, 1), breaks = c(0, 1),
                     labels=c("0" = "min", "1" = "max"), position = "bottom") +
  scale_y_continuous(limits = c(-2.5, 2), breaks=c(-2.5, -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0,  1.5, 2.0),
                     labels = c("-2.5", "-2.0", "-1.5", "-1.0", "-0.5", "0.0", "0.5",  "1.0", "1.5", "2")) +
  # ylim(0, 2) +
  theme_sjplot2() +
  geom_hline(yintercept = 0, color = "red", linetype = "dashed", linewidth=1.25) +
  ggtitle("(A)") +
  theme(axis.title.x = element_text(face="bold", size = 20, vjust=-4), 
        axis.title.y = element_text(face="bold", size = 20, vjust=4),
        axis.text.x = element_text(face="bold", size = 14, hjust=1),
        axis.text.y = element_text(face="bold", size = 14, hjust=1),
        plot.caption = element_text(size = 16, hjust = 1),
        plot.title = element_text(size = 20, face="bold", vjust=5, hjust=0.5),
        legend.title=element_text(size = 14, face = "bold"),
        legend.text=element_text(size = 14),
        plot.margin = unit(c(1,1,0.7,1), "cm"),
        legend.position=c(.22,.27))
panelA_fig4

##############################################################

# PANEL B: Predicted values

panelB_fig4<-plot_model(model8, type = "pred", terms = c("ei_index_vdem [all]", "conspi_nm [0, 1]"), 
               legend.title = "")+
  # Add labels for X and Y axes
  xlab("Electoral integrity (country level)") +
  ylab("Predicted values:\n Evaluation of national elections as free and fair (0-10)") +
  scale_color_manual(values = c("black", "grey60"), labels = c("Conspiracy beliefs: low", "Conspiracy beliefs: high")) +
  scale_fill_manual(values = c("black", "grey60")) +
  scale_x_continuous(limits = c(0, 1), breaks = c(0, 1),
                     labels=c("0" = "min", "1" = "max"), position = "bottom") +
  scale_y_continuous(breaks = c(0,2,4,6,8,10), limits = c(0,10)) + 
  theme_sjplot2() +
  ggtitle("(B)") +
  theme(
    axis.title.x = element_text(face="bold", size = 20, vjust=-4), 
    axis.title.y = element_text(face="bold", size = 20, vjust=4),
    axis.text.x = element_text(face="bold", size = 14, hjust=1),
    axis.text.y = element_text(face="bold", size = 14, hjust=1),
    plot.caption = element_text(size = 16, hjust = 1),
    plot.title = element_text(size = 20, face="bold", vjust=5, hjust=0.5),
    legend.title=element_text(size = 14, face = "bold"),
    legend.text=element_text(size = 14),
    plot.margin = unit(c(1,1,1,1), "cm"),
    legend.position=c(.71,.28))

panelB_fig4


##############################################################

# save Figure 4

fig4 <- ggarrange(panelA_fig4, panelB_fig4, ncol = 2)
fig4

ggsave(filename = "Fig4.pdf", 
       width=15, height=10, dpi = 1200) 

ggsave(filename = "Fig4.svg", 
       width=15, height=10, dpi = 1200) 

ggsave("Fig4.eps", device=cairo_ps, 
       width=15, height=10, fallback_resolution = 1200)

#############################################################################


# FIGURE S1

ggplot(ess, aes(x = conspi_nm, y = fairelcc)) +
  geom_ribbon(stat = "smooth", method = "lm", fill = "lightgrey", color = "NA") +
  geom_smooth(method = "lm", se = T, colour = "red", linewidth=0.4) +
  facet_wrap(~cname, nrow=5) +   # a panel for each mountain range
  labs(x = "Belief in conspiracy theories (0-1)", y = "Evaluation: national elections free and fair (0-10)", 
       title = "", col = "Country") + 
  theme_sjplot2() +
  scale_x_continuous(breaks = c(0, 1), labels=c("0" = "min", 
                                                "1" = "max"), position = "bottom") +
  theme(axis.text.x = element_text(face="bold", color="#000000", 
                                   size=12, angle=0)) +
  theme(axis.title.x = element_text(face="bold", size=18, color="#000000", 
                                    margin = margin(t = 10, r = 0, b = , l = 0))) +
  scale_y_continuous(limits = c(0, 10),breaks = c(0, 10), labels=c("0"="min", "10"="max")) +
  theme(axis.text.y = element_text(face="bold", color="#000000", 
                                   size=12, angle=45)) +
  theme(axis.title.y = element_text(face="bold", size=18, color="#000000", 
                                    margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  theme(strip.text = element_text(face = "bold", size=16)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(legend.position = "none",
        panel.spacing = unit(1, "lines"))


##############################################################

# save Figure S1
ggsave(filename = "FigS1.pdf", 
       width=13, height=11, dpi = 1200) 

ggsave(filename = "FigS1.svg", 
       width=13, height=11, dpi = 1200) 

#############################################################################


# FIGURE S2

summary(model6c)
summary(ess$conspi_nm)
table(ess$cname)

# get predicted values from model 6
pred.m6 <- ggpredict(model6c, terms = c("conspi_nm", "cname"),  type="random") # this gives predictions for countries
pred.m6

# plot figure S2
figS2<-plot(pred.m6, ci=F, facets=T, colors = "bw", line.size = 1) +
  scale_colour_grey() +
  scale_fill_grey() +
  labs(x = "Belief in conspiracy theories (0-1)", y = "Predicted values: Evaluation of national elections as free and fair (0-10)", 
       title = "", col = "Country") + 
  theme_sjplot2() +
  scale_x_continuous(breaks = c(-0.39638, 0.60362), labels=c("-0.39638" = "min", 
                                                             "0.60362" = "max"), position = "bottom") +
  theme(axis.text.x = element_text(face="bold", color="#000000", 
                                   size=12, angle=0)) +
  theme(axis.title.x = element_text(face="bold", size=18, color="#000000", 
                                    margin = margin(t = 10, r = 0, b = , l = 0))) +
  scale_y_continuous(breaks = c(4,6,8,10), limits = c(4,10)) + 
  theme(strip.text.x = element_text(face="bold", size=16)) +
  theme(strip.background = element_rect(fill = "white")) +
  theme(axis.text.y = element_text(face="bold", color="#000000", 
                                   size=12, angle=0)) +
  theme(axis.title.y = element_text(face="bold", size=18, color="#000000", 
                                    margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  theme(panel.spacing = unit(2, "lines"))

figS2

##############################################################

# save Figure S2
ggsave(filename = "FigS2.pdf", 
       width=14, height=12, dpi = 1200) 

ggsave(filename = "FigS2.svg", 
       width=14, height=12, dpi = 1200) 

#############################################################################


# FIGURE S3

summary(model9)

figS3<-plot_model(model9, type = "pred", terms = c("winner2 [all]", "conspi_nm [0, 1]"), 
                      line.size=2, dot.size=4, legend.title = "") +
  # Add labels for X and Y axes
  xlab("") +
  ylab("Predicted values:\n Evaluation of national elections as free and fair (0-10)") +
  scale_color_manual(values = c("black", "grey60"), labels = c("Conspiracy beliefs: low", "Conspiracy beliefs: high")) +
  #scale_alpha_manual(values=c(0.5, 0.9)) +
  scale_fill_manual(values = c("black", "grey60")) +
  scale_x_continuous(labels=c("Loser\n(L)", "Winner\n(W)", "Non-voter", "Voter\n(L/W unknown)", "Ineligible")) +
  scale_y_continuous(breaks = c(5,6,7,8,9,10), limits = c(5,10)) + 
  theme_sjplot2() +
  # Add the title
  ggtitle("") +
  theme(
    axis.title.x = element_text(face="bold", size = 18, vjust=-4), 
    axis.title.y = element_text(face="bold", size = 18, vjust=4),
    axis.text.x = element_text(face="bold", size = 16, hjust=0.5),
    axis.text.y = element_text(face="bold", size = 16, hjust=0),
    plot.caption = element_text(size = 16, hjust = 1),
    plot.title = element_text(size = 20, face="bold", vjust=5, hjust=0.5),
    legend.title=element_text(size = 14, face = "bold"),
    legend.text=element_text(size = 16),
    plot.margin = unit(c(1,1,1,1), "cm"),
    legend.position=c(.80,.85))

figS3

##############################################################

# save Figure S3

ggsave(filename = "FigS3.pdf", 
       width=10, height=8, dpi = 1200) 

ggsave(filename = "FigS3.svg", 
       width=10, height=8, dpi = 1200) 

##############################################################